/**
 * User: Obi
 * Date: 02.08.11
 * Time: 23:38
 */
package com.jediflasher.game_client.controller {
	import com.jediflasher.game_client.data.LoginData;
	import com.jediflasher.game_client.events.model.LoginDataEvent;
	import com.jediflasher.game_client.events.view.LoginViewEvent;
	import com.jediflasher.game_client.server.MessageWrapper;
	import com.jediflasher.game_client.server.ServerConnector;
	import com.jediflasher.game_client.server.messages.LoginRequest;
	import com.jediflasher.game_client.server.messages.MessageType;
	import com.jediflasher.game_client.server.messages.MethodLogin;
	import com.jediflasher.game_client.server.messages.ServiceType;
	import com.jediflasher.game_client.utils.logging.Logger;
	import com.jediflasher.game_client.utils.logging.LoggerEvent;
	import com.jediflasher.game_client.utils.logging.LoggerMessageLevel;
	import com.jediflasher.game_client.view.LoginView;

	public class LoginController extends BaseController {

		public function LoginController(serverConnector:ServerConnector, data:LoginData, view:LoginView) {
			super(serverConnector, data, view);

			view.addEventListener(LoginViewEvent.LOGIN, this.handler_login);

			data.addEventListener(LoginDataEvent.LOGIN_ERROR, this.handler_loginError);

			Logger.view.addEventListener(LoggerEvent.INPUT, this.handler_loggerInput);
		}

		private function sendLogin(login:String, password:String):void {
			var message:LoginRequest = new LoginRequest();
			message.login = login;
			message.password = password;

			super.send(MessageType.REQUEST, ServiceType.LOGIN, MethodLogin.LOGIN, message);
		}


		override protected function receiveMessage(messageWrapper:MessageWrapper):void {
			if (messageWrapper.serviceType != ServiceType.LOGIN) return;

			this.data.read(messageWrapper.message);
		}

		/**
		 * @private
		 */
		private function handler_login(event:LoginViewEvent):void {
			var login:String = event.login;
			var password:String = event.password;

			sendLogin(login, password);
		}

		/**
		 * @private
		 */
		private function handler_loggerInput(event:LoggerEvent):void {
			var text:String = event.text;
			if(text.indexOf("login") == 0) {
				var arr:Array = text.split(" ");
				if(arr.length < 3) {
					Logger.log("Incorrect login command arguments. try login <login> <password>", LoggerMessageLevel.ERROR);
				}else {
					var login:String = arr[1] as String;
					var password:String = arr[2] as String;
					this.sendLogin(login, password);
				}
			}
		}

		/**
		 * @private
		 */
		private function handler_loginError(event:LoginDataEvent):void {
			Logger.log("Wrong login or password", LoggerMessageLevel.ERROR);
		}
	}
}
